<template>
  <div>
    <van-cell @click="clickSuggestion(item)" v-for="item in suggestion" :key="item" icon="search">
      <div slot="title" v-html="formatStr(item)"></div>
    </van-cell>
  </div>
</template>

<script>
import { debounce } from 'lodash'
import { getSearchSuggestions } from '@/api/search.js'
export default {
  data () {
    return {
      setId: null,
      suggestion: '',
      isShow: true // 清空输入框不再发起请求
    }
  },
  props: {
    value: {
      type: String,
      required: true
    }
  },
  methods: {
    async loadSearchSuggestions () {
      try {
        const { data: res } = await getSearchSuggestions(this.value)
        // console.log(res)
        this.suggestion = res.data.options
      } catch (err) {
        this.$toast('获取数据失败')
      }
    },
    formatStr (item) {
      // 动态生成正则表达式
      const reg = new RegExp(this.value, 'gi')
      // 根据正则表达式进行匹配替换
      return item.replace(reg, '<span style="color:red;">' + this.value + '</span>')
    },
    clickSuggestion (item) {
      this.$emit('search', item)
    }
  },
  computed: {},
  watch: {
    value: {
      // value变化触发
      // handler (newVal) {
      //   clearTimeout(this.setId)
      //   this.setId = setTimeout(() => {
      //     console.log('获取联想建议')
      //   }, 900)
      // },
      handler: debounce(function (newVal) {
        if (!this.isShow) return
        this.loadSearchSuggestions()
      }, 900),
      // 首次触发
      immediate: true
    }
  },
  beforeDestroy () {
    this.isShow = false
  },
  filters: {},
  components: {},
  created () { },
  mounted () { }
}
</script>

<style scoped lang='less'>
</style>
